<template>
	<view class="productbody">
		<count-down
			v-if="showcount && isEnd"
			:ProductBody="ProductBody"
			:active="Active"
			@on-hide="gameOver"
		></count-down>
		<view class="top">
			<view class="int" v-if="!showcount || !isEnd">
				<view class="price">
					<text>&yen;</text>
					{{ ProductBody.now_price }} <block v-if="attr.length">- {{ ProductBody.orgin_price }}</block>
				</view>
				<image src="/static/integral.png" v-if="ProductBody.need_score"></image>
				<text class="min" v-if="ProductBody.need_score">+{{ ProductBody.need_score }}</text>
			</view>
			<view class="title">
				<view>{{ ProductBody.name }}</view>
				<image v-if="showcount && isEnd && ProductBody.need_score" src="/static/integral.png"></image>
			</view>
			<view class="sell" v-if="!showcount || !isEnd">
				<view>
					已售
					<text>:</text>
					{{ ProductBody.sell_count }}					
				</view>
				<view v-if="Active.islimit">
					<view class="cu-capsule radius">
						<view class='cu-tag bg-brown sm'>
							{{ Active.limit_days }}
						</view>
						<view class="cu-tag line-brown sm">
							天内限购{{ Active.limit_num }}件
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="x_x">
			<view v-if="coupon.length">
				<view class="attr">
					<view class="name">领券</view>
					<view class="showCoupon" @tap="isCoupon = true">
						<view class="coupon">
							<view v-for="i in showCoupon" :key="i.coupon_id">
								<image src="/static/c.png"></image>
								<text>满{{ i.NeedMoney }}减{{ i.MaxMoney }}</text>
								<image src="/static/c_b.png"></image>
							</view>
						</view>
						<view class="msg">共{{ coupon.length }}张</view>
					</view>
					<image src="/static/more.png"></image>
				</view>
			</view>
			<view>
				<view class="attr">
					<view class="name">已选</view>
					<view class="rst" @tap="value.show = show = true">
						<block v-if="selectAttr.length">
							<text>请选择</text>
							<text v-for="item in selectAttr" :key="item.id">{{ item.name }}</text>
						</block>
						<block v-else>
							<text>{{ selectedAttrName }}</text>
						</block>
					</view>
					<image src="/static/more.png"></image>
				</view>
			</view>
		</view>
		<evaluate-list :elist="evaluateList" :source="ProductBody" v-if="Active.is_open_evaluation"></evaluate-list>
		<view class="pros">
			<view
			@touchmove.stop.prevent="noEevent"
				@tap="value.show = show = false"
				:class="['dialog-backdrop', { 'backdrop-in': value.show }]"></view>
			<view @touchmove.stop.prevent="noEevent" :class="['contain', { 'modal-in': value.show }]">
				<view class="close" @tap="value.show = show = false"><image src="/static/close.png"></image></view>
				<view class="cover">
					<view
						class="defaultCover"
						:style="{ backgroundImage: 'url(' + ProductBody.default_imgurl + ')' }"
					></view>
					<view class="info">
						<view class="price">
							<block v-if="selectAttr.length">
								<text>&yen;</text>
								{{ ProductBody.now_price }} - {{ ProductBody.orgin_price }}
							</block>
							<block v-else>
								<text>&yen;</text>
								{{ selectAttrItem.now_price }}
							</block>
							<block v-if="selectAttrItem.need_score || ProductBody.need_score">
								<image src="/static/integral.png"></image>
								<block v-if="!selectAttr.length">
									<text class="integral">+{{ selectAttrItem.need_score }}</text>
								</block>
							</block>
						</view>
						<view class="item">
							<text class="name">库存：</text>
							<block v-if="selectAttr.length">
								<text>{{ ProductBody.storenum }}</text>
							</block>
							<block v-else>
								<text>{{ selectAttrItem.storenum }}</text>
							</block>
						</view>
						<view class="item please">
							<block v-if="selectAttr.length">
								<text class="name">请选择：</text>
								<text v-for="item in selectAttr" :key="item.id">
									{{ item.name }}
								</text>
							</block>
							<block v-else>
								<text class="name">已选择：</text>
								<text>{{ selectedAttrName }}</text>
							</block>
						</view>
					</view>
				</view>
				<view class="group">
					<scroll-view scroll-y class="srx">
						<view v-for="(item, idx) in attr" :key="idx" class="item">
							<view class="name">{{ item.name }}</view>
							<view class="attr">
								<view
									:class="{ act: k.checked }"
									v-for="(k, m) in item.parent_pros"
									:key="k.id"
									@tap="$emit('select', [idx, m])"
								>
									{{ k.name }}
								</view>
							</view>
						</view>
						<view class="item count">
							<view class="name">数量</view>
							<view class="attr">
								<uni-number-box
									:min="1"
									:max="max"
									:value="num"
									@change="buyNum"
								></uni-number-box>
							</view>
						</view>
					</scroll-view>
				</view>
				<view class="shop_com">
					<!-- #ifdef MP-WEIXIN -->
					<wx-auth :type="1" v-if="!userInfo" :link="{link: true}"></wx-auth>
					<!-- #endif -->						
					<block v-if="Active.is_privilege !== 2">
						<view
							:class="['addCart', { type: value.show && !value.type }]"
							@tap="addCart"
							v-if="!value.type || show">
							{{ show ? '加入购物车' : '确定' }}
						</view>
						<view class="buyBtn" @tap="buyBtn" v-if="value.type || show">
							{{ show ? '立即购买' : '下一步' }}
						</view>						
					</block>
					<block v-else>
						<view class="special">您没有特权购买此商品</view>
					</block>
				</view>
			</view>
		</view>
		<pro-desc :ProductBody="ProductBody"></pro-desc>
		<coupon-list :list="coupon" :show="isCoupon" @on-close="isCoupon = false"></coupon-list>
	</view>
</template>

<script>
import uniNumberBox from '@/components/uni-number-box';
import { checkeProducts } from '@/common/api'
import EvaluateList from './evaluatelist';
import CouponList from './couponlist';
import CountDown from './countdown';
import ProDesc from './prodesc';
import { mapGetters } from 'vuex';
export default {
	components: {
		uniNumberBox,
		EvaluateList,
		CouponList,
		CountDown,
		ProDesc
	},
	watch: {
		selectAttrItem(val, oldVal) {
			if (JSON.stringify(val) !== '{}') {
				this.num = this.selectNum = 1;
			}
		}
	},
	props: {
		RemainScore: Number, // 用户的积分,
		shopInfo: Object,
		ProductBody: {
			//商品基本信息
			type: Object,
			required: true
		},
		attr: {
			// 商品属性列表
			type: Array,
			required: true
		},
		attrPrice: {
			// 商品属性对应信息
			type: Array,
			required: true
		},
		evaluateList: {
			// 评论列表
			type: Array,
			required: true
		},
		coupon: {
			// 优惠券
			type: Array,
			required: true
		},
		Active: {
			// 活动信息
			type: Object,
			required: true
		}
	},
	created() {
		this.CartList = uni.getStorageSync('ShopCart') || []
		this.showcount = this.Active.issnapup || 0
		this.$bus.on('showProps', value => {
			if (JSON.stringify(this.selectAttrItem) !== '{}') {
				value ? this.buyBtn() : this.addCart()
			} else {
				this.value.show = true
				this.value.type = value				
			}
		})
	},
	destroyed () {
		this.$bus.off('showProps')
	},
	data() {
		return {
			value: {
				show: false,
				type: 0
			},
			popup: false,
			CartList: [], // 购物车产品
			items: {}, // 当前正在购买的产品
			isCoupon: false, // 优惠券弹窗
			show: false, // 是否显示商品属性窗口
			num: 1, // 默认商品的数量
			selectNum: 1, // 选择商品的数量
			showcount: 0 // 产品抢购活动
		};
	},
	computed: {
		...mapGetters(['userInfo', 'shop']),
		selectAttr() {
			// 需要选择的属性
			return this.attr.filter(item => {
				return !item.parent_pros.some(k => k.checked);
			});
		},
		selectedAttr() {
			// 已经选择的属性
			let result = this.attr.map(item => {
				let rst = item.parent_pros.filter(item => {
					return item.checked;
				});
				return rst[0] || {};
			});
			return result.filter(item => JSON.stringify(item) !== '{}');
		},
		selectedAttrName() {
			// 已选择属性的名称
			let name = this.selectedAttr
				.map(item => item.name)
				.toString()
				.replace(/,/gi, ' ');
			return name + ' ' + this.selectNum + '件';
		},
		selectedAttrId() {
			// 已选择属性的ID
			let ID = this.selectedAttr
				.map(item => item.id)
				.toString()
				.replace(/,/gi, '_');
			return ID;
		},
		selectAttrItem() {
			// 已选择完整商品的对应信息
			if (!this.attr.length) {
				return {
					id: '',
					need_score: this.ProductBody.need_score,
					now_price: this.ProductBody.now_price,
					orgin_price: this.ProductBody.orgin_price,
					prope: '',
					storenum: this.ProductBody.storenum
				}
			}
			return this.attrPrice.filter(item => item.id === this.selectedAttrId)[0] || {};
		},
		max() {
			if (JSON.stringify(this.selectAttrItem) !== '{}') {
				return this.selectAttrItem.storenum;
			}
			return 100;
		},
		showCoupon() {
			// 优惠券满减显示
			return this.coupon
				.filter(item => typeof item.NeedMoney === 'number')
				.filter((m, i) => i < 3);
		},
		isNeedScore() {
			// 购买改产品需要的积分是否足够， 不够返回false
			return this.selectAttrItem.need_score * this.selectNum <= this.RemainScore;
		},
		isEnd() {
			if (this.showcount) {
				let startTime = this.Active.buystart_time.replace(/-/gi, '/')
				let endTime = this.Active.countdown_time.replace(/-/gi, '/')
				let now = new Date().getTime()
				let End = new Date(endTime)
				if (now - new Date(startTime) < 0) return false
				return End > now
			}
			return false;
		}
	},
	methods: {
		noEevent () { // 废弃
		 },
		checkPro () {
			return new Promise(resolve => {
				if (this.CartList.length) {
					uni.showLoading({ mask: true })
					checkeProducts({ pid1: this.ProductBody.id, pid2: this.CartList[0].pid }).then(res => {
						uni.hideLoading()
						resolve(res.data)
					})						
				} else {
					resolve(1)
				}
			})
		},		
		closeAttr() {
			this.show = false;
			this.$emit('input', { show: false });
		},
		buyNum(value) {
			// 购买商品的数量
			this.selectNum = this.num = value;
		},
		gameOver() {
			this.showcount = 0;
		},
		 addCart() {
			// 加入购物车
			this.buyAuth(0).then(() => {
				this.checkPro().then(result => {				
						if (result !== 1 && result !== 40001) {
							uni.showModal({
								content: '此产品与购物车中商品的支付方式不相符,请单独购买',
								showCancel: false
							})
							return
						} else if (result === 40001) {
							uni.showModal({
								content: '此产品不能加入购物车，请单个购买',
								showCancel: false
							})
							return
						}
				if (this.shop.type === 5) {
					if (this.CartList.length) {					
						// 如果添加重复属性的商品，则只加数量
						let isAdd = -1;
						for (let i = 0; i < this.CartList.length; i++) {
							if (this.CartList[i].pid === this.items.pid && this.CartList[i].property_id === this.items.property_id) isAdd = i;
						}
						if (isAdd >= 0) {
							this.CartList[isAdd].rcount += this.items.rcount;
						} else {
							this.CartList.push(this.items);
						}
					} else {
						this.CartList.push(this.items);
					}
					uni.setStorageSync('ShopCart', this.CartList);
					uni.showToast({ title: '加入成功' });
				} else if (this.shop.type === 1) {
					let item = this.items
					let idx = (() => {
						for (let i = 0;i < this.CartList.length;i++) {
							if (this.CartList[i].shop.id === this.shopInfo.id) {
								return i
							}
						}
						return -1 // 没有在购物车里面找到相应的店铺
					})()
				   if (idx === -1)	{
					this.CartList.push({ shop: this.shopInfo, list: [item] })
					uni.setStorageSync('ShopCart', this.CartList)
					uni.showToast({ title: '加入成功' })						
				   } else {
					   let ix = (() => {
						   for (let i = 0;i < this.CartList[idx].list.length;i++) {
							   if (this.CartList[idx].list[i].id === item.id && this.CartList[idx].list[i].prope === item.prope && this.CartList[idx].list[i].property_id === item.property_id) {
								   return i
							   }
						   }
						   return -1
					   })()
					   if (ix !== -1) {
						   this.CartList[idx].list[ix].rcount++
						   uni.setStorageSync('ShopCart', this.CartList)
						   uni.showToast({ title: '加入成功' })
					   } else {
						   this.CartList[idx].list.push(item)
						   uni.setStorageSync('ShopCart', this.CartList)
						   uni.showToast({ title: '加入成功' })
					   }							   
				   }
				}
				this.$bus.emit('cartList', uni.getStorageSync('ShopCart'))											
				})
			})
		},
		buyBtn() {
			// 去购买
			this.buyAuth(1).then(() => {
				let data = []
				uni.setStorageSync('buyAddr', ''); // 清除收货地址ID				
				if (this.shop.type === 5) {
					data = [this.items]
				} else if (this.shop.type === 1) {
					data = [{list: [this.items], shop: this.shopInfo}]
				}
				uni.setStorageSync('items', data);
				uni.navigateTo({ url: '/pages/orders/create?type=0' });	
			})
		},
		is_line (type) { // 线上商城加入购物车，立即购买验证
			return new Promise(resolve => {
				if (!type && this.Active.is_virtual === 1) {
					uni.showModal({
						content: '虚拟物品不能加入购物车',
						showCancel: false
					})
					return								
				}
				if (!type && this.Active.pay_type === 1) {
					uni.showModal({
						content: '该产品是有指定的支付方式,不能加入购物车,只能单独购买',
						showCancel: false
					})
					return
				}
				if (this.Active.parent_id < 0) {
					uni.showModal({
						content: '您没有推荐人，不能购买',
						showCancel: false
					});
					return;
				}
				if (!this.isNeedScore) {
					uni.showModal({
						content: '您的会员积分不够',
						showCancel: false
					});
					return;
				}
				this.items = {
					decrease_money: 0,
					is_virtual: this.Active.is_virtual,
					pid: this.ProductBody.id, // 产品id
					pname: this.ProductBody.name, // 商品名字
					prope: this.selectAttrItem.prope.replace(/-/gi, ' '), // 产品属性名称
					property_id: this.selectAttrItem.id, // 产品属性Id
					rcount: this.selectNum, // 购买数量
					totalprice: this.selectNum * this.selectAttrItem.now_price, // 总价格
					need_score: this.selectAttrItem.need_score, //需要的积分
					remain_score: this.RemainScore, //用户积分
					default_imgurl: this.ProductBody.default_imgurl, // 产品图片
					supply_id: this.ProductBody.supply_id,
					remarks: this.ProductBody.remarks, // 产品备注
					renew_id: '',
					now_price: this.selectAttrItem.now_price, // 当前价格
					transform: 0,
					checked: true,
					pay_type: this.Active.pay_type,
					extend_money: this.Active.extend_money
				}
				resolve()
			})
		},
		buyAuth(type) {
			// 购买验证
			return new Promise(resolve => {
				if (this.selectAttr.length) {
					let attrName = ` ${this.selectAttr
						.map(item => item.name)
						.toString()
						.replace(/,/gi, ' ')}`;
					uni.showToast({
						icon: 'none',
						title: `请选择${attrName}`
					})
				} else {
					if (this.selectAttrItem.storenum) {
						if (!this.userInfo) {
							uni.navigateTo({ url: '/pages/login/index' });
							return
						} else {
							if (this.shop.type === 5) {
								this.is_line(type).then(() => {
									this.$bus.emit('close')
									resolve()								
								})
							} else if (this.shop.type === 1) {
								this.items = Object.assign({}, this.ProductBody)
								this.items.prope = this.selectAttrItem.prope.replace(/_/gi, ' ') // 产品属性名称
								this.items.property_id = this.selectAttrItem.id // 产品属性Id
								this.items.rcount = this.selectNum// 购买数量	
								this.$bus.emit('close')
								resolve()
							}
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: '库存不足>_<'
						})
					}
				}
			})
		}
	}
};
</script>

<style lang="less" scoped>
@import '../../../common/styles/variables.less';
.productbody {
	.price {
		color: @red;
		font-weight: bold;
		font-size: 36upx;
		display: flex;
		align-items: center;
		text {
			font-size: @minSize;
			font-weight: bold;
			padding-right: 5px;
		}
		image {
			width: 40upx;
			height: 40upx;
			display: block;
			margin-left: 15upx;
		}
		.integral {
			font-size: @minSize;
		}
	}
	.min {
		font-size: @minSize;
		color: @red;
		font-weight: 600;
	}
	.top {
		padding: 10px 15px;
		background: white;
		.int {
			display: flex;
			align-items: center;
			justify-content: space-between;
			view {
				flex: 1;
			}
			image {
				width: 50upx;
				height: 50upx;
				display: block;
				margin-left: 15upx;
			}
		}
		.title {
			display: flex;
			align-items: center;
			view {
				flex: 1;
				font-size: @title;
				line-height: 46upx;
				font-weight: 500;
				.twoLine(2);
			}
			image {
				width: 50upx;
				height: 50upx;
				display: block;
				margin-left: 15upx;
			}
		}
		.sell {
			display: flex;
			align-items: center;
			& > view {
				&:nth-of-type(1) {
					margin-right: 20upx;
				}
			}
			text {
				margin: 0 5px;
			}
			color: @gray;
			font-size: 24upx;
		}
	}
	.x_x {
		background-color: white;
		margin: 15upx 0;
		display: flex;
		flex-direction: column;
		flex-flow: column;
		& > view {
			flex:1;
			padding: 8upx 15upx;
			&:not(:last-of-type) {
				.border-bottom(15upx);
			}
			.attr {
				padding: 16upx 0;
				font-size: 28upx;
				display: flex;
				align-items: center;
				position: relative;
				& > image {
					position: absolute;
					width: 40upx;
					height: 40upx;
					right: 0;
					top: 50%;
					transform: translateY(-50%);
				}
				.name {
					color: @gray;
					width: 70upx;
				}
				.showCoupon {
					flex: 1;
					margin-right: 50upx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					.coupon {
						display: flex;
						& > view {
							display: flex;
							align-items: center;
							height: 34upx;
							box-sizing: border-box;
							border-top: 2upx solid @red;
							border-bottom: 2upx solid @red;
							& > text {
								font-size: @minSize;
								color: @red;
								padding: 0 14upx 0 10upx;
								transform: scale(0.9);
							}
							& > image {
								height: 34upx;
								display: block;
								&:first-of-type {
									width: 14upx;
								}
								&:last-of-type {
									width: 8upx;
								}
							}
						}
						& > view:not(:last-of-type) {
							margin-right: 20upx;
						}
					}
					.msg {
						font-size: @minSize;
						color: @gray;
					}
				}
				.rst {
					flex: 1;
					.twoLine(1);
					margin-right: 45upx;
					text {
						margin-right: 5px;
						&:first-of-type {
							margin-left: 5px;
						}
						&:last-of-type {
							margin-right: 0;
						}
					}
				}
			}
		}
	}
	.pros {
		overflow: hidden;
		.dialog-backdrop {
			position: fixed;
			left: 0;
			top: 0;
			width: 100%;
			height: calc(100%);
			background: rgba(0, 0, 0, 0.4);
			z-index: 666;
			visibility: hidden;
			opacity: 0;
			transition-duration: 0.4s;
			will-change: opacity;
			contain: strict;
			&.backdrop-in {
				visibility: visible;
				opacity: 1;
			}
		}
		.contain {
			background-color: white;
			z-index: 777;
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			top: 20%;
			display: flex;
			flex-direction: column;
			flex-flow: column;
			justify-content: space-between;
			transform: translate3d(0, 100%, 0);
			contain: layout;
			will-change: transform, opacity;
			opacity: 0;
			transition: transform 0.2s, opacity 0.2s;
			border-radius: 12px 12px 0 0;
			&.modal-in {
				opacity: 1;
				transform: translate3d(0, 0, 0);
			}
			.close {
				z-index: 666;
				background-color: white;
				contain: layout;
				border-radius: 50%;
				position: absolute;
				top: 10upx;
				padding: 10upx;
				right: 20upx;
				overflow: hidden;
				& > image {
					width: 30upx;
					height: 30upx;
					display: block;
				}
			}
			.cover {
				padding: 15px;
				display: flex;
				.defaultCover {
					margin-right: 20upx;
					.combackground(contain, center, center);
					width: 200upx;
					height: 200upx;
				}
				.info {
					flex: 1;
					font-size: 24upx;
					.item {
						font-size: 24upx;
						&.please {
							text {
								margin-right: 5px;
								&:last-of-type {
									margin-right: 0;
								}
							}
						}
						.name {
							color: #666;
						}
					}
				}
			}
			.group {
				flex: 1;
				overflow: hidden;
				.srx {
					height: 100%;
					.item {
						&.count {
							display: flex;
							justify-content: space-between;
							align-items: center;
							padding: 3px 0;
							.name {
								margin: 0 0 0 15px;
							}
							.attr {
								margin-right: 15px;
								& > view {
									margin: 0;
									padding: 0;
									background: none;
									border-radius: 0;
								}
							}
						}
						.name {
							font-size: 22upx;
							color: #666;
							margin: 0 15px;
							margin-bottom: 10px;
						}
						.attr {
							font-size: 28upx;
							color: #333;
							display: flex;
							flex-wrap: wrap;
							& > view {
								background: #f7f7f7;
								padding: 10upx 18upx;
								margin: 0 0 10px 15px;
								border-radius: 4px;
								font-size: @minSize;
								&.act {
									background: @red;
									color: white;
								}
							}
						}
					}
				}
			}
			.shop_com {
				height: 92upx;
				display: flex;
				& > view {
					flex: 1;
					display: flex;
					align-items: center;
					justify-content: center;
					height: 100%;
					font-size: 26upx;
					color: white;
					&.addCart {
						background-color: #ff9600;
						color:#333;
					}
					&.buyBtn {
						background-color: @red;
					}
					&.special {
						background-color: #f0c532;
						color: #333;						
					}
				}
			}
		}
	}
}
</style>
